package com.one.common.location_service.track;


import android.app.Notification;
import android.os.Build;

import com.amap.api.track.AMapTrackClient;
import com.amap.api.track.ErrorCode;
import com.amap.api.track.OnTrackLifecycleListener;
import com.amap.api.track.TrackParam;
import com.one.common.CommonApp;
import com.one.common.config.CMemoryData;
import com.one.common.utils.DelayUtils;
import com.one.common.utils.Logger;
import com.tencent.bugly.crashreport.CrashReport;

/**
 * Author: zhulunjun
 * Email: zhulunjun@qq.com
 * CreateDate: 2019/7/31 11:04
 * Description： 猎鹰服务开启关闭
 **/
public class TrackHandle {
    private String TAG = "猎鹰服务管理";
    private static AMapTrackClient aMapTrackClient;
    private static TrackHandle instance;

    public static TrackHandle getInstance() {
        if (instance == null) {
            instance = new TrackHandle();
            // 初始化猎鹰服务
            aMapTrackClient = new AMapTrackClient(CommonApp.getInstance());
            // 10秒记录一次，60秒上传一次
            aMapTrackClient.setInterval(10, 60);
        }
        return instance;
    }

    /**
     * 轨迹服务是否开启
     */
    private boolean isServiceRunning = false;
    /**
     * 轨迹服务是否开始采集
     */
    private boolean isGatherRunning = false;

    /**
     * 重试的次数，开启，暂停失败
     * 1秒重试一次，3秒结束重试
     * 返回异常到后台
     */
    private int restartServiceNum = 0;
    private Notification notification;

    /**
     * 开启猎鹰轨迹,并开启位置采集
     */
    public void startTrack(Notification notification) {
        this.notification = notification;
        // 开启服务
        if (!isServiceRunning) {
            TrackParam trackParam = new TrackParam(CMemoryData.getTrackBean().getSid(), CMemoryData.getTrackBean().getTid());
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                trackParam.setNotification(notification);
            }
            aMapTrackClient.startTrack(trackParam, onTrackListener);
        }


    }

    /**
     * 关闭猎鹰轨迹
     */
    public void stopTrack() {
        if (isServiceRunning && isGatherRunning) {
            aMapTrackClient.stopGather(onTrackListener);
        }
    }

    private OnTrackLifecycleListener onTrackListener = new SimpleOnTrackLifecycleListener() {
        @Override
        public void onBindServiceCallback(int status, String msg) {
            Logger.d(TAG, "onBindServiceCallback, status: " + status + ", msg: " + msg);
        }

        @Override
        public void onStartTrackCallback(int status, String msg) {
            if (status == ErrorCode.TrackListen.START_TRACK_SUCEE || status == ErrorCode.TrackListen.START_TRACK_SUCEE_NO_NETWORK) {
                // 成功启动
                Logger.d(TAG, "服务成功启动");
                isServiceRunning = true;
                // 开始采集
                if (!isGatherRunning) {
                    aMapTrackClient.setTrackId(CMemoryData.getTrackBean().getTrid());
                    aMapTrackClient.startGather(onTrackListener);
                }
            } else if (status == ErrorCode.TrackListen.START_TRACK_ALREADY_STARTED) {
                // 已经启动
                Logger.d(TAG, "服务已经启动");
                isServiceRunning = true;
            } else {
                Logger.d(TAG, "error onStartTrackCallback, status: " + status + ", msg: " + msg);

                DelayUtils.delay(2000, () -> {
                    if(restartServiceNum > 3){
                        restartServiceNum = 0;
                        CrashReport.postCatchedException(new Throwable(TAG+" "+"error onStartTrackCallback, status: " + status + ", msg: " + msg));
                    }else {
                        restartServiceNum++;
                        // 开启服务
                        startTrack(notification);
                    }
                });
            }
        }

        @Override
        public void onStopTrackCallback(int status, String msg) {
            if (status == ErrorCode.TrackListen.STOP_TRACK_SUCCE) {
                // 成功停止
                Logger.d(TAG, "停止服务成功");
                isServiceRunning = false;
                isGatherRunning = false;
            } else {
                Logger.d(TAG, "error onStopTrackCallback, status: " + status + ", msg: " + msg);
                DelayUtils.delay(1000, () -> {
                    if(restartServiceNum > 3){
                        restartServiceNum = 0;
                        CrashReport.postCatchedException(new Throwable(TAG+" "+"error onStopTrackCallback, status: " + status + ", msg: " + msg));
                    }else {
                        restartServiceNum++;
                        // 暂停服务
                        stopTrack();
                    }
                });
            }
        }

        @Override
        public void onStartGatherCallback(int status, String msg) {
            if (status == ErrorCode.TrackListen.START_GATHER_SUCEE) {
                Logger.d(TAG, "定位采集开启成功");
                isGatherRunning = true;
            } else if (status == ErrorCode.TrackListen.START_GATHER_ALREADY_STARTED) {
                Logger.d(TAG, "定位采集已经开启");
                isGatherRunning = true;
            } else {
                Logger.d(TAG, "error onStartGatherCallback, status: " + status + ", msg: " + msg);
                DelayUtils.delay(2000, () -> {
                    if(restartServiceNum > 3){
                        restartServiceNum = 0;
                        CrashReport.postCatchedException(new Throwable(TAG+" "+"error onStartGatherCallback, status: " + status + ", msg: " + msg));
                    }else {
                        restartServiceNum++;
                        // 开始采集
                        aMapTrackClient.setTrackId(CMemoryData.getTrackBean().getTrid());
                        aMapTrackClient.startGather(onTrackListener);
                    }
                });
            }
        }

        @Override
        public void onStopGatherCallback(int status, String msg) {
            if (status == ErrorCode.TrackListen.STOP_GATHER_SUCCE) {
                Logger.d(TAG, "定位采集停止成功");
                isGatherRunning = false;
                // 停止服务
                aMapTrackClient.stopTrack(new TrackParam(CMemoryData.getTrackBean().getSid(),
                        CMemoryData.getTrackBean().getTid()), onTrackListener);
            } else {
                Logger.d(TAG, "error onStopGatherCallback, status: " + status + ", msg: " + msg);
                DelayUtils.delay(1000, () -> {
                    if(restartServiceNum > 3){
                        restartServiceNum = 0;
                        CrashReport.postCatchedException(new Throwable(TAG+" "+"error onStopGatherCallback, status: " + status + ", msg: " + msg));
//                        CrashReport.
                    }else {
                        restartServiceNum++;
                        // 暂停采集
                        aMapTrackClient.stopGather(onTrackListener);
                    }
                });
            }
        }
    };


    public void removeTr(){
//        aMapTrackClient.d
    }


}
